<template>
  <div class="app-container calendar-list-container">
    <el-row>
      <el-col :span="4" style="margin-right:10px">
        <div class="lesson-cate">
          <div class="lesson-cate-title">课程分类</div>
          <div class="lesson-cate-content">
            <ul>
              <template>
                <li v-for="item in cateList" :key="item.class_2_id" v-bind:class="{ active: item.class_2_id === listQuery.class_2_id }">
                  <div style="width:83%" @click="changeCate(item.class_2_id)">
                    <p>{{item.class_2_name}}</p>
                    <p>{{item.class_1_name}}</p>
                    <span class="span-len">{{item.essay_num}}节</span>
                  </div>
                  <span class="span-update-icon" @click="openDialogForm('update',item.class_1_id,item.class_2_name,item.class_2_id)"><i class="el-icon-edit"></i></span>
                  <span class="span-delete-icon" @click="deleteCate(item.class_2_id,item.essay_num)"><i class="el-icon-delete"></i></span>
                </li>
              </template>
            </ul>
            <div class="plus-div">
              <el-button class="plus-btn" @click="openDialogForm('add')"><i class="el-icon-plus"></i></el-button>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="19">
        <div class="filter-container">
          <el-button type="primary" style="margin-right:20px;" @click="handleConfigure">配置阶段</el-button>
          <el-select class="filter-item" style="width: 130px" @change="getThreeList" v-model="listQuery.class_3_id" placeholder="所有阶段" @clear="clearTwo()">
            <el-option v-for="item in class3" :key="item.id" :label="item.class_name" :value="item.id">
            </el-option>
          </el-select>
          <span class="search-title">-</span>
          <el-select class="filter-item" style="width: 130px" @change="getList" v-model="listQuery.class_4_id" placeholder="所有阶段">
            <el-option v-for="item in class4" :key="item.id" :label="item.class_name" :value="item.id">
            </el-option>
          </el-select>
          <span class="search-title">课程名称</span>
          <el-input type="text" v-model="listQuery.keyword" @blur="getList" placeholder="请输入课程名称" clearable></el-input>
          <el-button type="primary" class="addBtn" @click="handleAdd">新增</el-button>
        </div>

        <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row
          style="width: 100%" max-height="580">
          <el-table-column width="60" align="center" label="编号">
            <template slot-scope="scope">
              <span>{{scope.row.id}}</span>
            </template>
          </el-table-column>
          <el-table-column width="220" align="center" label="阶段">
            <template slot-scope="scope">
              <span>{{scope.row.stage}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" min-width="220" label="名称">
            <template slot-scope="scope">
              <span>{{scope.row.title}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" width="100" label="测试">
            <template slot-scope="scope">
              <span v-if="scope.row.question_num">{{scope.row.question_num}}道</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column align="center" width="100" label="状态">
            <template slot-scope="scope">
              <span>{{scope.row.status_text}}</span>
            </template>
          </el-table-column>
          <el-table-column class-name="status-col" label="最后修改时间" width="180">
            <template slot-scope="scope">
              <span>{{scope.row.update_time | parseTime('{y}-{m}-{d} {h}:{i}:{s}')}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" width="100" label="最后修改人">
            <template slot-scope="scope">
              <span>{{scope.row.update_uid_text}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="320" class-name="small-padding">
            <template slot-scope="scope">
              <el-button type="view" size="mini" @click="handleView(scope.row)">查看</el-button>
              <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
              <el-button type="danger" size="mini" @click="handleDelete(scope.row,scope.$index)">删除</el-button>
              <el-popover
                placement="top"
                title=""
                width="80"
                trigger="hover"
                content="">
                <img :src="scope.row.qrcode"/>
                <el-button type="success" style="margin-left:10px" slot="reference" size="mini">预览</el-button>
              </el-popover>
            </template>
          </el-table-column>
        </el-table>

        <div v-show="!listLoading" class="pagination-container">
          <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page"
            :page-sizes="[5,10,20,30, 50]" :page-size="listQuery['per-page']" layout="total, sizes, prev, pager, next, jumper" :total="total">
          </el-pagination>
        </div>
      </el-col>
    </el-row>
    <el-dialog :title='dialogTitle' :visible.sync="dialogFormVisible" width="500px">
      <el-form :model="dialogForm" :rules="dialogRules" ref="dialogForm">
        <el-form-item label="类型" :label-width="formLabelWidth" prop="class_1_id">
          <el-select v-model="dialogForm.class_1_id" placeholder="请选择类型">
            <el-option
              v-for="item in dialogOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程分类id" :label-width="formLabelWidth" v-show="false">
          <el-input v-model="dialogForm.class_2_id"></el-input>
        </el-form-item>
        <el-form-item label="课程分类" :label-width="formLabelWidth" prop="class_2_name">
          <el-input v-model="dialogForm.class_2_name" placeholder="请输入课程名称"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogTitle === '新增课程分类'" type="primary" @click="confirmAdd()">确 定</el-button>
        <el-button v-if="dialogTitle === '编辑课程分类'" type="primary" @click="confirmUpdate()">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<style rel="stylesheet/scss" lang="scss"  scoped>
  .el-dialog {
    width: 40%!important;
  }
</style>

<style scoped>
  .el-popover, .el-popper {
    text-align: center!important;
  }
  .el-time-spinner__wrapper {
    vertical-align: inherit;
  }
  .filter-container .filter-item {
    margin-bottom: 4px;
  }
  .el-input {
    width: 200px;
  }
  .lesson-cate {
    width: 100%;
    min-height: 50vh;
    border: solid 1px #ebeef5;
  }
  .lesson-cate-title {
    padding: 0 15px;
    font-size: 14px;
    color: #999;
    line-height: 50px;
    border-bottom: solid 1px #ebeef5;
  }
  .lesson-cate-content ul {
    -webkit-margin-before: 0px;
    -webkit-margin-after: 0px;
    -webkit-padding-start: 0px;
  }
  .lesson-cate-content li {
    width: 100%;
    padding: 5px 15px 5px 15px;
    /*height: 50px;
    line-height: 20px;*/
    position: relative;
    list-style-type: none;
    border-bottom: solid 1px #ebeef5;
    -webkit-margin-before: 0px;
    -webkit-margin-after: 0px;
    cursor: pointer;
  }
  .lesson-cate-content li p {
    margin: 0px;
    font-size: 12px;
    color: #999;
  }
  .lesson-cate-content li p:first-child {
    font-size: 14px;
    color: #333;
    margin-top:3px;
    margin-bottom:10px;
  }
  .lesson-cate-content li span.span-len {
    position: absolute;
    font-size: 12px;
    right: 60px;
    bottom:5px;
    color: #666;
  }
  .lesson-cate-content li span.span-update-icon{
    position:absolute;
    right:35px;
    display: inline-block;
    bottom:5px;
    font-size:12px;
    color:#ed8a94;
  }
  .lesson-cate-content li span.span-delete-icon{
    position:absolute;
    right:10px;
    display: inline-block;
    bottom:5px;
    font-size:12px;
    color:#f00;
  }
  .lesson-cate-content .plus-div{
    text-align:center;
  }
  .lesson-cate-content .plus-btn{
    margin:30px auto 20px;
    background-color:#ed8a94;
    color:#fff;
    border:0;
    font-size:16px;
    width:40%;
  }
  .lesson-cate-content li:hover {
    background-color: #eee;
  }
  .lesson-cate-content li:last-child {
    border-bottom: none;
  }
  .lesson-cate-content li.active {
    background-color: #eee;
  }
  .addBtn{
    margin-left:100px;
  }
</style>

<script>
import { getLessonCate, getLessonList, getLessonStageOne, getLessonStageTwo, deleteEssay, classOneList, createOneClass, updateOneClass, deleteOneClass } from '@/api/science'
import waves from '@/directive/waves' // 水波纹指令
import { parseTime } from '@/utils'
import QRCode from 'qrcode'

export default {
  name: 'complexTable',
  directives: {
    waves
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      qrArr: [],
      total: null,
      listLoading: true,
      listQuery: {
        class_2_id: '',
        class_3_id: '',
        class_4_id: '',
        keyword: '',
        page: 1,
        'per-page': 10
      },
      cateList: [],
      temp: {
        id: undefined,
        username: '',
        account: '',
        phone: '',
        status: '',
        created_at: '',
        auth_key: ''
      },
      class3: [],
      class4: [],
      groupArr: [],
      dialogFormVisible: false,
      dialogStatus: '',
      downloadLoading: false,
      dialogForm: {
        class_2_name: '',
        class_1_id: '1',
        class_2_id: ''
      },
      dialogRules: {
        class_2_name: [
          { required: true, message: '请输入课程名称', trigger: 'blur' },
          { max: 20, message: '长度在10个字符以内', trigger: 'blur' }
        ],
        class_1_id: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ]
      },
      dialogTitle: '',
      formLabelWidth: '120px',
      dialogOptions: []
    }
  },
  created() {
    this.getLessonCate()
  },
  methods: {
    changeCate(id) {
      this.listQuery.class_2_id = id
      this.getList()
      this.getLessonStageOne() // 获取一阶段列表
      this.listQuery.class_3_id = ''
      this.listQuery.class_4_id = ''
    },
    getList() {
      this.listLoading = true
      getLessonList(this.listQuery).then(response => {
        this.list = response.data.data
        this.total = response.data._meta.totalCount
        this.listLoading = false
      }).then(() => {
        var obj = this
        for (const key in this.list) {
          QRCode.toDataURL(
            'http://yunxiao.daishujianbao.com/course/preview?id=' + this.list[key]['id'], {
              width: 125,
              height: 125
            }, function(err, url) {
              if (err) throw err
              obj.list[key].qrcode = url
            })
        }
      })
    },
    clearTwo() { // 清理第二个阶段列表
      this.listQuery.class_4_id = ''
      this.class4 = []
    },
    getLessonCate() {
      getLessonCate().then(response => {
        this.cateList = response.data
        this.listQuery.class_2_id = response.data[0].class_2_id
        this.getList() // 获取课程列表
        this.getLessonStageOne() // 获取一阶段列表
      })
    },
    getLessonStageOne() { // 获取第一个阶段列表
      getLessonStageOne({ class_2_id: this.listQuery.class_2_id }).then(response => {
        this.class3 = response.data
        this.class3.unshift({ 'id': '', 'class_name': '所有阶段' })
      })
    },
    getLessonStageTwo() { // 获取第一个阶段列表
      if (this.listQuery.class_3_id !== '') {
        getLessonStageTwo({ class_3_id: this.listQuery.class_3_id }).then(response => {
          this.class4 = response.data
          this.class4.unshift({ 'id': '', 'class_name': '所有阶段' })
        })
      }
    },
    getThreeList() {
      this.listQuery.class_4_id = ''
      this.getLessonStageTwo()
      this.getList()
    },
    userValue() {
      this.temp.account = this.temp.account.replace(/[^\d\w_]/ig, '')
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery['per-page'] = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        account: '',
        username: '',
        phone: '',
        password: '',
        status: ''
      }
    },
    // 查看课程
    handleView(row) {
      this.$router.push({ path: '/science/lesson-view/' + row.id })
    },
    // 编辑课程
    handleUpdate(row) {
      this.$router.push({ path: '/science/lesson-edit/' + row.id })
    },
    // 配置阶段
    handleConfigure() {
      this.$router.push({ path: '/science/lesson-configure/' })
    },
    // 新增课程
    handleAdd() {
      this.$router.push({ path: '/science/lesson-add/' })
    },
    // 删除课程
    handleDelete(row, index) {
      this.$confirm('此操作将永久删除课程, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteEssay(Object.assign({}, { 'id': row.id })).then(response => {
          if (response.data.code === '200') {
            this.getList()
            this.$message({
              message: '删除成功',
              type: 'success'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 课程分类添加按钮
    openDialogForm(str, id1, name, id2) {
      this.dialogFormVisible = true
      classOneList().then(response => {
        this.dialogOptions = response.data
      })
      if (str === 'add') {
        this.dialogTitle = '新增课程分类'
        this.dialogForm = {
          class_2_name: '',
          class_1_id: '1'
        }
      } else if (str === 'update') {
        this.dialogTitle = '编辑课程分类'
        this.dialogForm = {
          class_2_name: name,
          class_1_id: id1,
          class_2_id: id2
        }
      }
    },
    showCode(id) {
      this.show.splice(id, 1, true)
    },
    // 删除课程分类
    deleteCate(class_2_id, num) {
      this.$confirm('此操作将永久删除课程分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (num === 0) {
          deleteOneClass(Object.assign({}, { 'class_2_id': class_2_id })).then(response => {
            this.getLessonCate()
            this.$message.success('删除成功')
          })
        } else {
          this.$message.warning('当前课程分类下有课程，不能删除')
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 新增课程分类
    confirmAdd() {
      this.$refs['dialogForm'].validate((valid) => {
        if (valid) {
          createOneClass(Object.assign({}, { 'class_1_id': this.dialogForm.class_1_id }, { 'class_2_name': this.dialogForm.class_2_name })).then(response => {
            this.dialogFormVisible = false
            this.getLessonCate()
            this.$message({
              message: '添加成功',
              type: 'success'
            })
          })
        } else {
          return false
        }
      })
    },
    // 编辑课程分类
    confirmUpdate() {
      this.$refs['dialogForm'].validate((valid) => {
        if (valid) {
          updateOneClass(Object.assign({}, this.dialogForm)).then(response => {
            this.dialogFormVisible = false
            this.getLessonCate()
            this.$message({
              message: '修改成功',
              type: 'success'
            })
          })
        } else {
          return false
        }
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
